package com.geely.config;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.amqp.core.Message;

import java.util.Objects;


public class HandleService implements ChannelAwareMessageListener {

    /**
     * @param message, channel
     * 1、处理成功，这种时候用basicAck确认消息；
     * 2、可重试的处理失败，这时候用basicNack将消息重新入列；
     * 3、不可重试的处理失败，这时候使用basicNack将消息丢弃。
     *
     *  basicNack(long deliveryTag, boolean multiple, boolean requeue)
     *   deliveryTag:该消息的index
     *  multiple：是否批量.true:将一次性拒绝所有小于deliveryTag的消息。
     * requeue：被拒绝的是否重新入队列
     */
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long timeMillis = System.currentTimeMillis();
        System.out.println(timeMillis + "队列=" + message.getMessageProperties().getConsumerQueue());
        System.out.println(timeMillis + "标识=" + message.getMessageProperties().getDeliveryTag());
        System.out.println(timeMillis + "交换机=" + message.getMessageProperties().getReceivedExchange());
        System.out.println(timeMillis + "路由=" + message.getMessageProperties().getReceivedRoutingKey());
        byte[] body = message.getBody();
        System.out.println("接收到消息:" + new String(body));
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(new String(body));

            if (jsonObject.getBoolean("type")) {
                System.out.println("消息消费成功");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);//确认消息消费成功
            } else if (!jsonObject.getBoolean("type")) {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } else if (Objects.isNull(jsonObject.get("msg"))){          //消费失败
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            }
        } catch(Exception e){
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);//消息丢弃
                System.out.println("This message:" + jsonObject + " conversion JSON error ");
            }

    }
}